package com.course.web.page;

import com.course.auth.SecurityUtils;
import com.course.web.view.*;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.*;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Justin on 2017/5/12.
 */
@SpringUI(path = "/admin")
public class AdminUI extends UI {

    private final ViewDisplayPanel panel;

    @Autowired
    public AdminUI(ViewDisplayPanel panel) {
        this.panel = panel;
    }

    @Override
    protected void init(VaadinRequest request) {
        HorizontalLayout root = new HorizontalLayout();
        Panel navigation = new Panel("功能导航");
        VerticalLayout action = new VerticalLayout();
        Button student = new Button("学生管理");
        Button teacher = new Button("老师管理");
        Button spec = new Button("模板管理");
        Button course = new Button("课程管理");
        Button exam = new Button("测验管理");
        Button logout = new Button("退出登录");
        Button home = new Button("返回首页");

        root.addComponent(navigation);
        root.addComponentsAndExpand(panel);
        navigation.setContent(action);
        action.addComponent(student);
        action.addComponent(teacher);
        action.addComponent(spec);
        action.addComponent(course);
        action.addComponent(exam);
        action.addComponent(logout);
        action.addComponent(home);
        setContent(root);
        setSizeFull();

        root.setSizeFull();
        navigation.setWidthUndefined();
        panel.setSizeFull();
        panel.setCaption("管理后台");

        student.addClickListener(event -> jump(StudentListView.NAME, "学生管理"));
        teacher.addClickListener(event -> jump(TeacherListView.NAME, "老师管理"));
        spec.addClickListener(event -> jump(SpecListView.NAME, "模板管理"));
        course.addClickListener(event -> jump(CourseListView.NAME, "课程管理"));
        exam.addClickListener(event -> jump(ExamInfoView.NAME, "测验管理"));
        logout.addClickListener(event -> logout());
        home.addClickListener(event -> home());

        getNavigator().setErrorView(AccessDeniedView.class);
        getPage().setTitle("管理后台");
    }

    private void jump(String name, String title) {
        getNavigator().navigateTo(name);
        panel.setCaption(title);
    }

    private void home() {
        getPage().setLocation("/");
    }

    private void logout() {
        SecurityUtils.logout();
        getPage().reload();
        getSession().close();
    }
}
